package org.stvd.service.message.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.common.enums.MessageStatusEnum;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.IdWorker;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.message.BsMessageLog;
import org.stvd.repository.message.BsMessageLogDao;
import org.stvd.service.base.impl.BaseServiceImpl;
import org.stvd.service.message.BsMessageLogService;

/**
 * @Title: BsMessageLogServiceImpl
 * @Description: 消息记录业务层实现类
 * @author houzx
 * @date 2020年9月18日
 */
@Service("BsMessageLogService")
public class BsMessageLogServiceImpl extends BaseServiceImpl<BsMessageLog> implements BsMessageLogService{

    @Resource(name = "BsMessageLogDao")
    private BsMessageLogDao bsMessageLogDao;
    
    @Override
    public QueryResult<Map<String, Object>> queryMessageResult(int start, int limit, 
        String recId, String type, String status) {
        return bsMessageLogDao.queryMessageResult(start, limit, recId, type, status);
    }

    @Override
    public Map<String, Object> getMessageByLogId(Long logId) {
        if(logId!=null) {
            return bsMessageLogDao.getMessageByLogId(logId);
        }
        return null;
    }
    
    @Override
    @Transactional
    public int updateMessageStatus(String messageLogIds, String status) {
        if(!StringUtil.isEmpty(messageLogIds) && !StringUtil.isEmpty(status)) {
            return bsMessageLogDao.updateMessageStatus(messageLogIds, status);
        }
        return -1;
    }
    
    @Override
    @Transactional
    public int syncUpdateMessage(String recId) {
        int count = 0;
        if(!StringUtil.isEmpty(recId)) {
            List<Map<String, Object>> list = bsMessageLogDao.listUnSyncMessage(recId);
            if (list != null && list.size() > 0) {
                BsMessageLog sysMessageLog = null;
                for (Map<String, Object> map : list) {
                    sysMessageLog = new BsMessageLog();
                    sysMessageLog.setId(IdWorker.getInstance().nextId());
                    sysMessageLog.setRecId(recId);
                    sysMessageLog.setMessageId(Long.parseLong(map.get("messageId").toString()));
                    sysMessageLog.setStatus(MessageStatusEnum.UnRead.getValue());
                    bsMessageLogDao.insert(sysMessageLog);
                    count++;
                }
            }
        }
        return count;
    }
    
    @Override
    public Long countUnreadMessage(String recId) {
        if(!StringUtil.isEmpty(recId)) {
            syncUpdateMessage(recId);
            return bsMessageLogDao.countUnreadMessage(recId);
        }
        return Long.parseLong("-1");
    }
}
